/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.bht.esa.weather.frontend;

import de.bht.esa.weather.usermanager.FrontendUser;
import de.bht.esa.weather.usermanager.UserManager;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import javax.naming.InitialContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

/**
 * Stellt alle Funktionen für das Usermanagement via REST bereit.
 * 
 * @author andreas
 */
@Path("user")
public class UserResource {

    UserManager userManager;
    @Context
    private UriInfo context;

    public UserResource(@Context SecurityContext sc) throws Exception {
        InitialContext ctx = new InitialContext();
        this.userManager = (UserManager) ctx.lookup("java:global/de.bht.esa.weather_WeatherAppFrontend_war_1.0-SNAPSHOT/UserManager");
    }

    @GET
    @Produces("application/json")
    @Path("/{id}")
    @RolesAllowed({"ADMIN"})
    public Response getUser(@PathParam("id") int id) {
        FrontendUser tmp = userManager.getUser(id);
        if(tmp==null){
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        return Response.ok(tmp).build();
    }

    @GET
    @Produces("application/json")
    @Path("/")
    @RolesAllowed({"ADMIN"})
    public Response getAllUsers() {
        List<FrontendUser> users = userManager.getUsers(null);
        return Response.ok(users.toArray(new FrontendUser[users.size()])).build();
    }

    @PUT
    @Consumes("application/json")
    @Path("/")
    @RolesAllowed({"ADMIN"})
    public Response add(String body) throws Exception {
        JSONObject jsonUserObject = new JSONObject(body);
        FrontendUser fU = new FrontendUser();
        
        String name = jsonUserObject.getString("name");
        String password = jsonUserObject.getString("password");
        String userRole = jsonUserObject.getString("userRole");
        String eMail = jsonUserObject.getString("email");
        
        if(!userRole.equals("ADMIN") && !userRole.equals("USER")){
            return Response.status(Response.Status.BAD_REQUEST).build();
        }
        
        if(userManager.getUsers(name).isEmpty()){
            fU.setName(name);
            fU.setPasswordMD5(password);
            fU.setUserRole(userRole);
            fU.setEmail(eMail);
            userManager.saveUser(fU);
            return Response.ok("Done").build();
        }else{
            return Response.status(Response.Status.CONFLICT).build();
        }
    }
    
    @POST
    @Produces("application/json")
    @Consumes("application/json")
    @Path("/{id}")
    @RolesAllowed({"ADMIN"})
    public Response edit(String body, @PathParam("id") int id) throws Exception {
        JSONObject jsonUserObject = new JSONObject(body);
        FrontendUser fU = userManager.getUser(id);
        
        if(fU != null){
            if(jsonUserObject.has("name") && userManager.getOneUser(jsonUserObject.getString("name")) == null){
                String name = jsonUserObject.getString("name");
                fU.setName(name);
            }else{
                return Response.status(Response.Status.CONFLICT).build();
            }
            if(jsonUserObject.has("password")){
                String password = jsonUserObject.getString("password");
                fU.setPasswordMD5(password);
            }
            if(jsonUserObject.has("userRole")){
                String userRole = jsonUserObject.getString("userRole");
                fU.setUserRole(userRole);
            }
            userManager.saveUser(fU);
            return Response.ok("Done").build();
        }else{
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }

    @DELETE
    @Produces("application/json")
    @Path("/{id}")
    @RolesAllowed({"ADMIN"})
    public Response removeUser(@PathParam("id") int id) throws Exception {
        FrontendUser tmpUser = userManager.getUser(id);
        
        if(tmpUser==null){
            return Response.status(Response.Status.NOT_FOUND).build();
        }
        
        try{
            userManager.removeUser(tmpUser);
        }catch(Exception ex){
            return Response.status(Response.Status.FORBIDDEN).build();
        }
        return Response.ok("Done").build();
    }
}